package com.maserb.monitor.web.schoolStudent;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.maserb.monitor.common.*;
import com.maserb.monitor.entity.JwOrgEntity;
import com.maserb.monitor.entity.Role;
import com.maserb.monitor.entity.SysCode;
import com.maserb.monitor.entity.UserEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentEntity;
import com.maserb.monitor.entity.schoolStudent.SchoolStudentParentImportModel;
import com.maserb.monitor.entity.schoolStudent.SchoolTimeTableEntity;
import com.maserb.monitor.entity.schoolStudent.StudentAchieveEntity;
import com.maserb.monitor.enums.SchoolTimeTableDayEnum;
import com.maserb.monitor.enums.SchoolTimeTypeEnum;
import com.maserb.monitor.model.StudentAchieveScoreModel;
import com.maserb.monitor.service.base.IToolService;
import com.maserb.monitor.service.jwEducation.JwOrgService;
import com.maserb.monitor.service.schoolStudent.SchoolStudentService;
import com.maserb.monitor.service.schoolStudent.SchoolTimeTableService;
import com.maserb.monitor.service.schoolStudent.StudentAchieveService;
import com.maserb.monitor.service.sysCode.SysCodeService;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 学生成绩
 */
@Controller
@RequestMapping("/studentAchieve")
public class StudentAchieveController {


    @Autowired
    StudentAchieveService achieveService;

    @Autowired
    SysCodeService sysCodeService;

    @Autowired
    JwOrgService orgService;

    @Autowired
    SchoolStudentService studentService;

    @Autowired
    IToolService toolService;

    @Value("${monitor.studentAchieveUrl}")
    private String studentAchieveUrl;


    @RequestMapping(value = {"/", "/index"})
    public ModelAndView getIndex(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("student_achieve/index");
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        String userId = user.getId();
        view.addObject("userId",userId);
        return view;
    }

    @RequestMapping("/list")
    @ResponseBody
    public PageResponseResult<StudentAchieveEntity> doList(HttpServletRequest request,PageRequestParam page,String userId, String name,String studentId, final String term, final String clazzId) {
        Sort.Order codeOrder = new Sort.Order(Sort.Direction.DESC, "createTime");
        List<Sort.Order> orderList = new ArrayList<Sort.Order>();
        orderList.add(codeOrder);
        Sort sort = new Sort(orderList);
        return AjaxUtils.processPage(page,sort, new Func_T1<PageRequest, Page<StudentAchieveEntity>>() {
            @Override
            public Page<StudentAchieveEntity> invoke(PageRequest var1) throws Exception {
                HttpSession session = request.getSession(true);
                UserEntity user = (UserEntity) session.getAttribute("user");
                String userId = user.getId();
                Page<StudentAchieveEntity> page = achieveService.findAll(var1,userId,name,studentId,term,clazzId);
                if(null!=page){
                    for(StudentAchieveEntity entity : page.getContent()){
                        if(!StringUtils.isEmptyOrWhitespace(entity.getClazzId())){
                            entity.setClazzId(toolService.getOrgName(entity.getClazzId()));
                        }
                    }
                }
                return page;
            }
        });
    }

    @RequestMapping("/getAddAchieve")
    public ModelAndView getAddAchieve(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("student_achieve/add");
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        List<SchoolStudentEntity>studentList = studentService.findByUser(user);
        view.addObject("studentList",studentList);
        return view;
    }

    @RequestMapping("/doAddAchieve")
    @ResponseBody
    public AjaxResult<Boolean> doAddAchieve(HttpServletRequest request, StudentAchieveEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                HttpSession session = request.getSession(true);
                UserEntity user = (UserEntity) session.getAttribute("user");
                if(null==user){
                    return false;
                }else{
                    entity.setCreateUser(user.getId());
                }
                entity.setCreateTime(new Date());
                achieveService.save(entity);
                return true;
            }
        });
    }

    @RequestMapping("/getUpdateAchieve/{id}")
    public ModelAndView getEditAchieve(final HttpServletRequest request,@PathVariable final String id) {
        ModelAndView view = new ModelAndView();
        view.setViewName("student_achieve/edit");
        StudentAchieveEntity entity = achieveService.findOne(id);
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        List<SchoolStudentEntity>studentList = studentService.findByUser(user);
        view.addObject("studentList",studentList);
        view.addObject("entity",entity);
        return view;
    }

    @RequestMapping("/doUpdateAchieve")
    @ResponseBody
    public AjaxResult<Boolean> doUpdateAchieve(StudentAchieveEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                StudentAchieveEntity achieveEntity = achieveService.findOne(entity.getId());
                achieveEntity.setStudent(entity.getStudent());
                achieveEntity.setClazzId(entity.getClazzId());
                achieveEntity.setTerm(entity.getTerm());
                achieveEntity.setUpdateTime(new Date());
                achieveService.save(achieveEntity);
                return true;
            }
        });
    }

    @RequestMapping("/doDeleteAchieve")
    @ResponseBody
    public AjaxResult<Boolean> doDeleteAchieve(@RequestParam(value = "keys[]") ArrayList<String> keys) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                keys.forEach(id -> achieveService.delete(id));
                return true;
            }
        });
    }

    @RequestMapping("/getAddAchieveByTerm")
    public ModelAndView getAddAchieveByTerm(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.setViewName("student_achieve/add_term");
        HttpSession session = request.getSession(true);
        UserEntity user = (UserEntity) session.getAttribute("user");
        return view;
    }

    @RequestMapping("/doAddAchieveByTerm")
    @ResponseBody
    public AjaxResult<Boolean> doAddAchieveByTerm(HttpServletRequest request, StudentAchieveEntity entity) {
        return AjaxUtils.process(new Func_T<Boolean>() {
            @Override
            public Boolean invoke() throws Exception {
                HttpSession session = request.getSession(true);
                UserEntity user = (UserEntity) session.getAttribute("user");
                String createUser = "";
                String term = entity.getTerm();
                String clazzId = entity.getClazzId();
                Date createTime = new Date();
                if(null==user){
                    return false;
                }else{
                    createUser = user.getId();
                }
                List<SchoolStudentEntity> studentEntityList = studentService.findByClazzId(clazzId);
                List<StudentAchieveEntity> achieveEntityList = new ArrayList<StudentAchieveEntity>();
                if(null!=studentEntityList && studentEntityList.size()>0){
                    for(SchoolStudentEntity studentEntity : studentEntityList){
                        StudentAchieveEntity achieveEntity = new StudentAchieveEntity();
                        achieveEntity.setStudent(studentEntity);
                        achieveEntity.setCreateTime(createTime);
                        achieveEntity.setCreateUser(createUser);
                        achieveEntity.setClazzId(clazzId);
                        achieveEntity.setTerm(term);
                        achieveEntityList.add(achieveEntity);
                    }
                }
                if(achieveEntityList.size()>0){
                    achieveService.save(achieveEntityList);
                }
                return true;
            }
        });
    }

    //学生成绩导入
    @RequestMapping("/goFileUpload")
    public ModelAndView goFileUpload(final HttpServletRequest request) {
        ModelAndView view = new ModelAndView();
        view.addObject("studentAchieveUrl",studentAchieveUrl);
        view.setViewName("student_achieve/file_upload");
        return view;
    }

    @RequestMapping("/fileUpload")
    @ResponseBody
    public String fileUpload(final HttpServletRequest request, HttpServletResponse response, MultipartFile myfiles, String term) throws IOException {
        ImportParams params = new ImportParams();
        params.setTitleRows(1);
        params.setHeadRows(1);
        params.setNeedVerfiy(false);
        String resultStr = "导入成功";
        try {
            ExcelImportResult result = ExcelImportUtil.importExcelMore(myfiles.getInputStream(),StudentAchieveScoreModel.class,params);
            List<StudentAchieveScoreModel> list = result.getList();
            if(null!=list && list.size()>0){
                achieveService.saveByFile(list,term);
            }
        } catch (Exception e) {
            return "导入失败！";
        }
        return resultStr;
    }

}
